# -*- coding: utf-8 -*-

'''
/**
 * @file        AzKeyboard.py
 * @brief       XXXX
 * @note        XXXX
 * @author      靳普诏(puzhao.jin@hopechart.com)
 * @date        2024/06/01
 * @version     1.0

 * @par         修改日志
 * <table>
 * <tr><th>Date         <th>Version     <th>Author      <th> Description
 * <tr><td>2024/06/01   <td>1.0         <td>靳普诏       <td> 创建初始版本
 * @copyright   xxxx
 */
'''

import sys
import os
import argparse

from datetime import datetime
# 获取当前日期
CURR_DATE_STRING = datetime.now().strftime("%Y-%m-%d")
# 获取当前时间
CURR_TIME_STRING = datetime.now().strftime("%H:%M:%S")
## 获取当前脚本所在的目录
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# 输出目录路径
# print("SCRIPT_DIR: "+ SCRIPT_DIR)


import keyboard
import platform
import signal
import sys
import threading


class StopRequestChecker:
    '''
    # 示例用法
    checker = StopRequestChecker()

    while not checker.IsStopRequest():
        # 这里放置需要检测停止请求的代码逻辑
        pass
    '''
    def __init__(self, check_interval_ms=100):
        # 设置信号处理程序以检测CTRL+C的线程安全处理
        signal.signal(signal.SIGINT, self._safe_handle_sigint)

        # 初始化退出标志并加锁
        self._should_stop = False
        self._lock = threading.Lock()

    def _safe_handle_sigint(self, signum, frame):
        with self._lock:
            # 当检测到SIGINT信号（CTRL+C）时设置退出标志
            self._should_stop = True

    def IsStopRequest(self):
        """
        检测是否按键 'q' 'ESC' 或 CTRL+C
        :return: 如果检测到停止请求则返回True，否则返回False
        """
        try:
            with self._lock:
                # 对于Windows和Unix，使用不同的方法来检测按键
                if platform.system() == "Windows":
                    if keyboard.is_pressed("q") or keyboard.is_pressed("esc"):
                        return True
                else:
                    if self._should_stop:
                        return True

            # 持续检测按键
            # 调整等待时间以平衡响应速度和性能消耗
            keyboard.on_press(self._check_keyboard_events)

            return False

        except Exception as e:
            # 更细致的异常处理
            print(f"An error occurred while checking for stop request: {e}")
            # 对于无法恢复的错误，考虑是否应该终止程序或者其他处理方式
            return False

    def _check_keyboard_events(self, event):
        # 检测特定的按键事件，加锁保证线程安全
        with self._lock:
            if event.name in ['q', 'Escape']:
                self._should_stop = True















if __name__ == "__main__":


    ## 获取脚本传参
    argv = sys.argv
    argc = len(argv)
    # 打印命令行参数
    #for i in range(1, argc):
        #print("参数", i, ":", argv[i])


    # 设置命令行参数解析器
    # parser = argparse.ArgumentParser(description='Filter log file based on keywords.')
    # parser.add_argument('input_file', type=str, help='Input log file path')
    # parser.add_argument('output_file', type=str, help='Output filtered log file path')
    # parser.add_argument('filter_list', nargs='+', type=str, help='List of keywords to filter')

    # 解析命令行参数
    # args = parser.parse_args()

        
    print("============= BIGEN: AzKeyboard.py =============")



    print("============= END: AzKeyboard.py =============")



## Generated on "2024-06-01 18:18:58" by the tool "gen_hq_file.py >> V20231119" 

